const app = getApp();

Page({
  data: {
    currentCity: '定位中...',
    locationDesc: '',
    currentWeather: {},
    dailyForecast: [],
    isLoading: true,
    showSearchModal: false,
    searchKeyword: '',
    searchResults: []
  },

  onLoad: function() {
    this.getWeatherByLocation();
  },

  // 通过位置获取天气
  getWeatherByLocation: function() {
    const that = this;
    const location = app.globalData.userLocation;
    
    if (location) {
      // 获取城市信息
      that.getCityByLocation(location.latitude, location.longitude);
    } else {
      // 如果无法获取位置，使用默认城市
      that.setData({
        currentCity: '北京市',
        locationDesc: '中国'
      });
      that.getWeatherData('101010100'); // 北京的城市ID
    }
  },

  // 根据经纬度获取城市信息
  getCityByLocation: function(lat, lon) {
    const that = this;
    const apiKey = app.globalData.weatherApiKey;
    
    wx.request({
      url: `https://geoapi.qweather.com/v2/city/lookup?location=${lon},${lat}&key=${apiKey}`,
      success: function(res) {
        if (res.data.code === '200' && res.data.location.length > 0) {
          const city = res.data.location[0];
          that.setData({
            currentCity: city.name,
            locationDesc: `${city.adm2}, ${city.adm1}`
          });
          that.getWeatherData(city.id);
        } else {
          that.setData({
            currentCity: '北京市',
            locationDesc: '中国'
          });
          that.getWeatherData('101010100');
        }
      },
      fail: function() {
        that.setData({
          currentCity: '北京市',
          locationDesc: '中国'
        });
        that.getWeatherData('101010100');
      }
    });
  },

  // 获取天气数据
  getWeatherData: function(cityId) {
    const that = this;
    const apiKey = app.globalData.weatherApiKey;
    
    that.setData({ isLoading: true });
    
    // 获取实时天气
    wx.request({
      url: `https://devapi.qweather.com/v7/weather/now?location=${cityId}&key=${apiKey}`,
      success: function(res) {
        if (res.data.code === '200') {
          that.setData({
            currentWeather: {
              temp: res.data.now.temp,
              feelsLike: res.data.now.feelsLike,
              text: res.data.now.text,
              humidity: res.data.now.humidity,
              windSpeed: res.data.now.windSpeed,
              pressure: res.data.now.pressure
            }
          });
        }
      },
      complete: function() {
        that.setData({ isLoading: false });
      }
    });
    
    // 获取7天天气预报
    wx.request({
      url: `https://devapi.qweather.com/v7/weather/7d?location=${cityId}&key=${apiKey}`,
      success: function(res) {
        if (res.data.code === '200') {
          // 处理日期格式
          const forecast = res.data.daily.map(item => {
            const date = new Date(item.fxDate);
            const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            return {
              ...item,
              fxDate: `${(date.getMonth() + 1)}/${date.getDate()} ${weekDays[date.getDay()]}`
            };
          });
          that.setData({ dailyForecast: forecast });
        }
      }
    });
  },

  // 显示搜索模态框
  showSearchModal: function() {
    this.setData({ showSearchModal: true });
  },

  // 隐藏搜索模态框
  hideSearchModal: function() {
    this.setData({ 
      showSearchModal: false,
      searchKeyword: '',
      searchResults: []
    });
  },

  // 城市输入
  onCityInput: function(e) {
    this.setData({ searchKeyword: e.detail.value });
  },

  // 搜索城市
  searchCity: function() {
    const that = this;
    const keyword = this.data.searchKeyword.trim();
    const apiKey = app.globalData.weatherApiKey;
    
    if (!keyword) {
      wx.showToast({
        title: '请输入城市名称',
        icon: 'none'
      });
      return;
    }
    
    wx.request({
      url: `https://geoapi.qweather.com/v2/city/lookup?location=${keyword}&key=${apiKey}`,
      success: function(res) {
        if (res.data.code === '200' && res.data.location.length > 0) {
          that.setData({ searchResults: res.data.location });
        } else {
          that.setData({ searchResults: [] });
          wx.showToast({
            title: '未找到相关城市',
            icon: 'none'
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '搜索失败',
          icon: 'none'
        });
      }
    });
  },

  // 选择城市
  selectCity: function(e) {
    const city = e.currentTarget.dataset.city;
    this.setData({
      currentCity: city.name,
      locationDesc: `${city.adm2}, ${city.adm1}`
    });
    this.getWeatherData(city.id);
    this.hideSearchModal();
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    this.getWeatherByLocation();
    wx.stopPullDownRefresh();
  }
});